package handler

import (
	"2301a/live_broadcast/api/request"
	"2301a/live_broadcast/internal/dao"
	"2301a/live_broadcast/internal/model"
	"github.com/gin-gonic/gin"
	"net/http"
)

func AddLiveRoom(c *gin.Context) {
	var req request.AddLiveRoomReq

	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "参数信息错误",
			"data": err.Error(),
		})
		return
	}
	var user model.User
	userId := c.GetUint("userId")
	dao.GetOneById(userId, &user)
	if user.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "用户不存在",
			"data": nil,
		})
		return
	}
	dao.Create(&model.LiveRoom{
		Title:   req.Title,
		Info:    req.Info,
		FileUrl: req.FileUrl,
		UserId:  userId,
	})
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "实现新增直播间成功",
		"data": true,
	})
}

func DetailsLiveRoom(c *gin.Context) {

	var req request.DetailsLiveRoomReq

	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "参数信息错误",
			"data": err.Error(),
		})
		return
	}
	var user model.User
	userId := c.GetUint("userId")
	dao.GetOneById(userId, &user)
	if user.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "用户不存在",
			"data": nil,
		})
		return
	}
	var liveRoom model.LiveRoom
	dao.GetOneById(req.Id, &liveRoom)
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "查询其详细信息成功",
		"data": liveRoom,
	})
}

func ModifyLiveRoom(c *gin.Context) {

	var req request.ModifyLiveRoomReq

	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "参数信息错误",
			"data": err.Error(),
		})
		return
	}
	var user model.User
	userId := c.GetUint("userId")
	dao.GetOneById(userId, &user)
	if user.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "用户不存在",
			"data": nil,
		})
		return
	}
	var liveRoom model.LiveRoom
	dao.Update(&model.LiveRoom{
		Id:      req.Id,
		Title:   req.Title,
		Info:    req.Info,
		FileUrl: req.FileUrl,
		UserId:  userId,
	})
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "修改直播间信息成功",
		"data": liveRoom,
	})
}

func DeleteLiveRoom(c *gin.Context) {

	var req request.DeleteLiveRoomReq

	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "参数信息错误",
			"data": err.Error(),
		})
		return
	}
	var user model.User
	userId := c.GetUint("userId")
	dao.GetOneById(userId, &user)
	if user.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "用户不存在",
			"data": nil,
		})
		return
	}
	dao.Delete(&model.LiveRoom{Id: req.Id, UserId: userId})
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "移除指定直播间成功",
		"data": true,
	})
}
